#!/bin/bash

# 删除ara文件的文件头

function usage() {
    echo "Usage: $( basename $0 ) [-l <file_list>] [<file> ...]]"
    echo "     删除ara文件的文件头"
    echo "     -l <file_list>: 对文件列表里的每一个文件(一行)做删除操作"
    echo "     <file>...: 对给出的文件进行操作"
}

function rm_header_cpp() {
    local f="$1"

    # 检查37行是不是// ------
    line37=$( sed -n '37p' $f )
    if [[ "$line37" =~ \/\/[[:space:]]+------ ]]
    then
        # 删除文件头,代之以greenstone_header
        sed -i -e '37a\/\/ @greenstone_header@' -e '1,37d' "$f"
    fi
}

function rm_header_sharp() {
    local f="$1"

    # 检查37行是不是#  ------
    line37=$( sed -n '37p' $f )
    if [[ "$line37" =~ \#[[:space:]]+------ ]]
    then
        # 删除文件头,代之以greenstone_header
        sed -i -e '37a# @greenstone_header@' -e '1,37d' "$f"
    fi
}

function rm_header_sh() {
    local f="$1"

    # 检查39行是不是#  ------
    line39=$( sed -n '39p' $f )
    if [[ "$line39" =~ \#[[:space:]]+------ ]]
    then
        # 删除文件头,代之以greenstone_header
        sed -i -e '39a# @greenstone_header@' -e '3,39d' "$f"
    fi
}

function rm_header_j2() {
    local f="$1"

    # 检查39行是不是#  ------
    line37=$( sed -n '37p' $f )
    if [[ "$line37" =~ "The word AUTOSAR and the AUTOSAR logo" ]]
    then
        # 删除文件头,代之以greenstone_header
        sed -i -e '38a@greenstone_header@' -e '2,38d' "$f"
    fi
}

fs=()

while getopts ":l:" opt
do
    case "${opt}" in 
        l)
            # 注意,这里不能使用cat <file> | while read line
            # 因为cat命令会导致新shell的启动, 导致fs变成新shell的变量
            while read line
            do
                if [[ "${line}" =~ (^[ \t]*#.*) ]]
                then
                    # 忽略注释行
                    continue
                else
                    fs[${#fs[@]}]="$line"
                fi
            done < $OPTARG
            ;;
        ?)
            echo "Error: Unknown options: ${OPTARG}"
            usage
            ;;
    esac
done

# 读入其他的文件
shift $(( $OPTIND - 1 ))
while [ $# -gt 0 ]
do
    fs[${#fs[@]}]="$1"
    shift
done

for f in "${fs[@]}"
do
    echo "Work on $f"
    bn=$( basename "$f" )
    if [[ "${bn}" =~ \.cmake || "${bn}" =~ CMakeLists\.txt || "${bn}" =~ CMakeLists_.*\.txt || "${bn}" =~ \.py ]] 
    then
        rm_header_sharp "$f"
    elif [[ "${bn}" =~ \.sh ]]
    then
        rm_header_sh "$f"
    elif [[ "${bn}" =~ \.j2 ]]
    then
        rm_header_j2 "$f"
    else 
        rm_header_cpp "$f"
    fi
done
